
var appBody = angular.module('bodyApp', ['ui.router', 'ngSanitize', "ngNotify", 'CommonServiceMod', 'ApiServiceMod']);
appBody.constant('myConfig',{
    isOtherNav: window.location.href.indexOf('others.html') > 0,
    dataFromType: localStorage.getItem('dataFromType') == null ? 0 : +localStorage.getItem('dataFromType')
})
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
    menus.forEach(menu => {
        $stateProvider.state(menu.stateName, {
            url: menu.url,
            templateUrl: menu.templateUrl,
            controller: menu.controller,
            controllerAs: menu.controllerAs
        });
        menu.children?.forEach(child => {
            $stateProvider.state(child.stateName, {
                url: child.url,
                templateUrl: child.templateUrl,
                controller: child.controller,
                controllerAs: child.controllerAs
            });
        })
    });
    $urlRouterProvider.otherwise('/tools/baijiaxing');
}]).config(function($sceProvider){
	$sceProvider.enabled(false);
});

appBody.controller('bodyCtrl', ['$scope', '$location', '$state', function($scope, $location, $state) {    
    this.$state = $state;
    this.$location = $location;
    console.log(this.$state);
    
    $scope.menuList = menus;
    $scope.themeMode = localStorage.getItem('data-bs-theme') == null ? 'light' : localStorage.getItem('data-bs-theme');
    $scope.changeThemeMode = function(theme) {
        localStorage.setItem('data-bs-theme', theme);
        $scope.themeMode = theme;
    }
}]);

appBody.controller('homeCtrl', ['$scope', "$location", "$timeout", "ngNotify", "apiService", function($scope, $location, $timeout, ngNotify, apiService) {
    
}]);

appBody.controller('newCtrl', ['$scope', "$location", "$timeout", "ngNotify", "apiService", function($scope, $location, $timeout, ngNotify, apiService) {
    this.name = 'newCtrl';
}]);

appBody.controller('toolsCtrl', ['$scope', "$location", "$timeout", "ngNotify", "apiService", function($scope, $location, $timeout, ngNotify, apiService) {
    this.name = 'toolsCtrl';
    $scope.menuTools = [
        {
            name: 'Common Tools',
            icon: 'fa fa-home',            
            status: 1,
            children: [
                {
                    name: '百家姓加密',
                    stateName: 'tools.baijiaxing',
                    icon: 'fa fa-home',
                    status: 1
                 }, {
                    name: '小红书去水印',
                    stateName: 'tools.xiaohongshu',
                    icon: 'fa fa-home',
                    status: 1
                 }
            ]
        }
    ];
}]);

appBody.controller('bjxCtrl', ['$scope', "$location", "$timeout", "ngNotify", "apiService", function($scope, $location, $timeout, ngNotify, apiService) {
    this.name = 'bjxCtrl';
    $scope.inputText = "";
    $scope.outputText = '';
    $scope.copied = false;

    $scope.encode = function() {
        $scope.outputText = encode($scope.inputText);
    }
    $scope.decode = function() {
        $scope.outputText = decode($scope.inputText);
    }
    $scope.copy = function() {
        copyToClipboard($scope.outputText);
        $scope.copied = true;
        $timeout(function() {
            $scope.copied = false;
        }, 1000);
    }
}]);

appBody.controller('xhsCtrl', ['$scope', "$location", "$timeout", "ngNotify", "maskService", "apiService", function($scope, $location, $timeout, ngNotify, maskService, apiService) {
    this.name = 'xhsCtrl';
    loadCSS("./pages/tools/xiaohongshu.css");
    loadScript("./assets/tabler/libs/tom-select/dist/js/tom-select.base.min.js", function() {
        loadScript("./pages/tools/xiaohongshu.js");
    });        
    loadScript("./assets/tabler/libs/fslightbox/index.js");
    $scope.browserInfo = detectDeviceAndOS();
    
    $scope.inputText = "";
    $scope.outputText = '';
    $scope.copied = false;
    $scope.formImg = [];
    //$scope.images = ["http://192.168.50.4:8000/download/63a7b9fb000000002702a630_66e4361a0000000012012a40_15.png"];
    $scope.images = [];
    var opusName = "";
    const similarCharsRegex = /[\u2728\u2747\u2733\u2734\u2735\u2736\u2737\u2738\u2739\u273A\u273B\u273C\u273D\u273E\u273F\u2740\u2741\u2742\u2743\u2744\u2745\u2746]/g;

    $scope.parseShare = function() {
        if ($scope.inputText.trim() == "") {
            ngNotify.set("请输入分享链接", {
                type: "warn"
            });
            return false;
        }
        var opusIndexs = tomSelectIndex.getValue() == "" ? [] : tomSelectIndex.getValue().split(",").map(Number);
        if (opusIndexs.length > 0) {
            var pass = true;
            opusIndexs.forEach(opusIndex => {
                pass = pass && /^\d+$/.test(opusIndex)
            });
            if (!pass) {
                ngNotify.set("请输入正确的作品序号", {
                    type: "error"
                });
                return false;
            }
        }

        $scope.images = [];
        maskService.show("解析需花费一段时间，请耐心等待");
        apiService.parseXHS($scope.inputText.trim(), opusIndexs).then(res => {
            console.log(res);
            if (res.data != null) {
                opusName = res.data["作品标题"];            
                res.data["FileNames"].forEach(file => {
                    $scope.images.push("/xhsapi/download/" + file);
                    $scope.formImg.push(false);
                })
            } else {
                ngNotify.set(res.message, {
                    type: "warn"
                });
            }

            maskService.hide();
        }).catch(err => {
            ngNotify.set(err, {
                type: "warn"
            });
            maskService.hide();
        });
    }
    $scope.fromClipboard = function() {
        pasteFromClipboardSync().then(txt => {
            $scope.inputText = txt;
            $scope.$apply();
        }).catch(err => {
            ngNotify.set(err, {
                type: "warn"
            });
        });
    }
    $scope.downloadImages = function() {
        console.log($scope.formImg)
        maskService.show();
        $scope.formImg.forEach(function(checked, index) {
            if (checked) {
                downloadFile($scope.images[index], `${opusName}_${index + 1}.png`).then(res => {
                    if (!res) {
                        ngNotify.set(`下载第${index + 1}张图片失败`, {
                            type: "warn"
                        });
                    }
                });
            }
            $scope.formImg[index] = false;
        })
        maskService.hide();
    }
    
    const downloadImage = async (urls, name) => {
        let result = [];
        for (const [index, url] of urls.entries()) {
            result.push(await downloadFile(url, `${name}_${index + 1}.png`));
        }
        if (!result.every(item => item === true)) {
            alert("下载文件失败！");
        }
    };

    const downloadFile = async (link, filename) => {
        try {
            // 使用 fetch 获取文件数据
            let response = await fetch(link, {
                method: "GET",
            });

            // 检查响应状态码
            if (!response.ok) {
                console.error(`请求失败，状态码: ${response.status}`, response.status);
                return false
            }

            let blob = await response.blob();

            // 创建 Blob 对象的 URL
            let blobUrl = window.URL.createObjectURL(blob);

            // 创建一个临时链接元素
            let tempLink = document.createElement('a');
            tempLink.href = blobUrl;
            tempLink.download = filename;

            // 模拟点击链接
            tempLink.click();

            // 清理临时链接元素
            window.URL.revokeObjectURL(blobUrl);

            return true
        } catch (error) {
            console.error(`下载失败 (${filename}):`, error);
            return false
        }
    }
}]);